package io.zhengsh.javase;

import java.util.HashMap;
import java.util.Map;

public class TwoSumDemo {
    public static void main(String[] args) {
        int[] nums = new int[]{2, 7, 11, 15};

        int target = 9;

        int[] myIndex = twoSum1(nums, target);
        if (myIndex != null) {
            for (int item : myIndex) {
                System.out.println(item);
            }
        }
    }

    public static int[] twoSum1(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (target - nums[i] == nums[j]) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[2];
    }

    public static int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int partnerNumer = target - nums[i];
            if (map.containsKey(partnerNumer)) {
                return new int[]{i, map.get(partnerNumer)};
            }
            map.put(nums[i], i);
        }
        return new int[2];
    }
}
